package com.miao.hong.fang.user;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.apache.struts.validator.DynaValidatorActionForm;

import com.miao.hong.fang.IConstants;
import com.miao.hong.fang.user.service.UserService;
import com.miao.hong.fang.util.SecurityUtil;
import com.miao.hong.fang.util.SpringBeansHolder;
import com.miao.hong.fang.util.Utils;

public class UserAction extends DispatchAction{

	private UserService userService = SpringBeansHolder.getInstance().getUserService();
	
	public ActionForward initRegister(ActionMapping mapping, ActionForm form, HttpServletRequest request,
            HttpServletResponse response) {
		
		String[] ages = new String[31];
		for(int i = 0; i < 31; i++) {
			ages[i] = String.valueOf(i + 20);
		}
		request.setAttribute("ages", ages);
		return mapping.findForward("success");
	}
	
	public ActionForward checkUserId(ActionMapping mapping, ActionForm form, HttpServletRequest request,
            HttpServletResponse response) throws IOException {
		
		String userId = request.getParameter("userId");
		boolean valid = userService.checkUserId(userId);
		response.getWriter().write(String.valueOf(valid));
		return null;
	}
	
	public ActionForward validateCode(ActionMapping mapping, ActionForm form, HttpServletRequest request,
            HttpServletResponse response) throws IOException {
		String code = request.getParameter("code");
		if(code.toUpperCase().equals((String)request.getSession().getAttribute("genValidateCode"))) {
			response.getWriter().write(String.valueOf(true));
		}
		return null;
	}
	
	public ActionForward registerUser(ActionMapping mapping, ActionForm form, HttpServletRequest request,
            HttpServletResponse response) throws Exception {
		
		if(request.getSession().getAttribute("userId") != null) {
			response.sendRedirect(request.getContextPath() + "/index.jsp");
			return null;
		}
		
		DynaValidatorActionForm dynaForm = (DynaValidatorActionForm) form;
		UserTO user = (UserTO) dynaForm.get("user");
		
		if("miaohongfang".equalsIgnoreCase(user.getLoginName()) || "gaoshuaidage".equalsIgnoreCase(user.getLoginName())) {
			user.setIsAdmin("Y");
		}
		
		userService.registerUser(user);
		
		//JMSUtil.sendMsg(user);
		
		return mapping.findForward("success");
	}
	
	public ActionForward mypage(ActionMapping mapping, ActionForm form, HttpServletRequest request,
            HttpServletResponse response) {
		
		List courseList = null;
		
		DynaValidatorActionForm dynaForm = (DynaValidatorActionForm) request.getAttribute("registerForm");		
		if(dynaForm != null) {
			UserTO user = (UserTO) dynaForm.get("user");
			request.getSession().setAttribute("userId", user.getUserId());
			request.getSession().setAttribute("loginName", user.getLoginName());
			request.getSession().setAttribute("isAdmin", user.isAdmin());
			courseList = userService.getUserSubscribed(user.getUserId());
		} else {
			String userId = (String) request.getSession(false).getAttribute("userId");
			courseList = userService.getUserSubscribed(userId);
		}
		
		request.setAttribute("courseList", courseList);
		request.setAttribute("count", courseList.size());
		return mapping.findForward("success");
	}
	
	public ActionForward login(ActionMapping mapping, ActionForm form, HttpServletRequest request,
            HttpServletResponse response) throws Exception {
		
		String loginName = request.getParameter("userName");
		String pwd = request.getParameter("password");
		
		UserTO user = userService.getUserByLoginName(loginName);
		if(user != null) {
			
			//verify the password
			StringBuffer sb = new StringBuffer();
			sb.append(pwd).append("-").append(user.getLoginName()).append("-").append(Utils.timestampToString(user.getCreatedDt(), IConstants.DATE_TIME_FORMAT));
			if(SecurityUtil.encryptPwd(sb.toString()).equalsIgnoreCase(user.getPassword())) {
				//log access info
				UserAccessInfoTO to = userService.getAccessInfo(request.getSession().getId());
				if(to != null) {
					to.setLoginName(loginName);
					userService.updateAccessInfo(to);
				}
				
				request.getSession().setAttribute("userId", user.getUserId());
				request.getSession().setAttribute("loginName", user.getLoginName());
				request.getSession().setAttribute("isAdmin", user.isAdmin());
				
				//write loginName to cookie
				Cookie cookie = new Cookie("loginName", loginName);
				cookie.setMaxAge(7 * 24 *60 *60);
				response.addCookie(cookie);
				response.getWriter().write(String.valueOf(true));
			}
		}
		return null;
	}
	
	public ActionForward logout(ActionMapping mapping, ActionForm form, HttpServletRequest request,
            HttpServletResponse response) throws IOException {
		
		HttpSession session = request.getSession();
		session.invalidate();
		
		response.sendRedirect(request.getContextPath() + "/index.jsp");
		return null;
	}
	
	public ActionForward subscribeCourse(ActionMapping mapping, ActionForm form, HttpServletRequest request,
            HttpServletResponse response) throws IOException {
		String courseId = request.getParameter("courseId");
		String userId = (String) request.getSession().getAttribute("userId");
		
		userService.subscribeCourse(userId, courseId);
		response.getWriter().write(String.valueOf(true));
		return null;
	}
	
	public ActionForward cancelSubscribeCourse(ActionMapping mapping, ActionForm form, HttpServletRequest request,
            HttpServletResponse response) {
		DynaValidatorActionForm dynaForm = (DynaValidatorActionForm) form;
		String[] selection = (String[]) dynaForm.get("deleteSelection");
		
		userService.cancelSubscribeCourse((String) request.getSession().getAttribute("userId"), selection);
		
		return mapping.findForward("success");
	}
}
